package org.amphiprion.descentv2assistant.adapter;

import java.util.List;

import org.amphiprion.descentv2assistant.R;
import org.amphiprion.descentv2assistant.entity.Act;
import org.amphiprion.descentv2assistant.filter.IdFilter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ActAdapter extends BaseAdapter {
	private final List<Act> acts;
	private final IdFilter filter;

	private final LayoutInflater inflater;

	public ActAdapter(Context context, List<Act> acts, IdFilter filter) {
		this.inflater = LayoutInflater.from(context);
		this.acts = acts;
		this.filter = filter;

	}

	@Override
	public int getCount() {
		return acts.size();
	}

	@Override
	public Act getItem(int index) {
		return acts.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int index, View view, ViewGroup viewGroup) {
		ViewHolder vh = null;
		if (view == null) {
			vh = new ViewHolder();
			LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.item_trait, null);
			vh.img = (ImageView) ll.findViewById(R.id.trait_image);
			vh.txt = (TextView) ll.findViewById(R.id.trait_text);
			vh.chk = (CheckBox) ll.findViewById(R.id.trait_chk);
			view = ll;
			view.setTag(vh);
		} else {
			vh = (ViewHolder) view.getTag();
		}
		final Act t = getItem(index);
		final CheckBox cb = vh.chk;
		vh.txt.setText(t.name);
		vh.chk.setOnCheckedChangeListener(null);
		if (filter == null || filter.contains("" + t.value)) {
			vh.chk.setChecked(true);
		} else {
			vh.chk.setChecked(false);
		}
		vh.txt.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				cb.setChecked(!cb.isChecked());
			}
		});
		vh.chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean checked) {
				filter.checkTrait("" + t.value);
			}
		});
		// App.setImage(vh.img, t);

		return view;
	}

	class ViewHolder {
		ImageView img;
		TextView txt;
		CheckBox chk;
		String id;
	}

}
